package com.probiz.estore.common.model.product;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.probiz.estore.common.model.inventory.Inventory;
import com.probiz.estore.common.model.product.base.ProductSkuTbl;
import com.probiz.estore.common.service.PromoService;
import com.probiz.estore.core.util.ContextUtil;
import com.probiz.estore.product.ProductConstants;
import com.probiz.estore.product.service.ProdMainManager;
import com.probiz.estore.sales.engine.PRule;

/**
 * Model class for ProductSku. Add not database mapped fileds in this class.
 * 商品单品
 */
public class ProductSku extends ProductSkuTbl implements Cloneable{
	
	private BigDecimal discountPrice ;
	//*RAM用于暂时保存促销规则模拟运行后的结果
	private BigDecimal discountPriceRAM = new BigDecimal(0);
	private boolean isCatalogConditionGiftRAM = false;
	
	//是否已对该商品打折
	private boolean hasDiscount = false;
	//用于记录影响sku的单条促销规则
	private PRule prule = null;
	//用于记录售价(特价或者折扣价)比原价折扣了多少
	private BigDecimal discountPercent ;
	
	private String optionValueIds ="" ; //用于临时保存规格值id的字符串，形如 1,2,4,

	//保存获得赠送礼品的ID
	private String giftValueIds = "";
	/**
	 * 获得价格的显示方式
	 * 永远只会见到两个价
	 * 1.市场价、售价
	 * 2.售价、特价
	 * 3.售价、折扣价
	 * 4.售价、售价
	 * 5.原价、捆绑售价（商品包特有）(捆绑售价由特价、折扣价、售价依此决定)
	 * 
	 * 注意：在执行这两个方法前必须先计算折扣价
	 */
	
  	public Short getPriceViewType() {
  		short priceViewType ;
  		if(this.getProduct().getProductKind().equals(Product.PRODUCTKIND_PACKAGE)){
  			priceViewType = ProductConstants.PRICE_VIEW_TYPE_5;
  		}else if (this.getSalePrice() != null) {
			priceViewType = ProductConstants.PRICE_VIEW_TYPE_2;
		} else if (this.getDiscountPrice()!=null && this.getDiscountPrice().compareTo(this.getPrice()) != 0) {
			priceViewType = ProductConstants.PRICE_VIEW_TYPE_3;
		} else if (this.getListPrice() != null) {
			priceViewType = ProductConstants.PRICE_VIEW_TYPE_1;
		} else {
			priceViewType = ProductConstants.PRICE_VIEW_TYPE_4;
		}
		return priceViewType;
	}
  	/**
  	 * 是否可以查看批发价
  	 * @return
  	 */
  	public boolean isWholesalePriceAvailable(){
  		PromoService promoService = (PromoService) ContextUtil.getSpringBeanById("promoService");
  		ProductSku sku = promoService.appendPromoInfo(this);
  		if (sku.getSalePrice() != null) {
			return false;
		} else {
			return true;
		}
  		
  	}
  	/**
	 * 永远只会见到两个价
	 * 1.市场价、售价
	 * 2.售价、特价
	 * 3.售价、折扣价
	 * 4.售价、售价
	 * 5.原价、捆绑售价（商品包特有）(捆绑售价由特价、折扣价、售价依此决定)
	 * 
	 * 注意：在执行这两个方法前必须先计算折扣价
	 * 
	 * @return BigDecimal[0]去掉状态的价，BigDecimal[1]真实的价 
	 */
  	public BigDecimal[] getViewPrices(){
  		switch(getPriceViewType()){
  			case ProductConstants.PRICE_VIEW_TYPE_1:
  				return new BigDecimal[]{getListPrice(),getPrice()};
  			case ProductConstants.PRICE_VIEW_TYPE_2:
  				return new BigDecimal[]{getPrice(),getSalePrice()};
  			case ProductConstants.PRICE_VIEW_TYPE_3:
  				return new BigDecimal[]{getPrice(),getDiscountPrice()};
  			case ProductConstants.PRICE_VIEW_TYPE_4:
  				return new BigDecimal[]{getPrice(),getPrice()};
  			case ProductConstants.PRICE_VIEW_TYPE_5:
  				BigDecimal formerPrice = new BigDecimal("0");
  				//注意先获得product的默认货品，再取得商品包items
  				for(ProductPackageItem item : this.getProduct().getDefaultProductSku().getProductPackageItems()){
  					ProductSku itemSku = item.getItemSku();
  					PromoService promoService = (PromoService) ContextUtil.getSpringBeanById("promoService");
  					promoService.appendPromoInfo(itemSku);
  					formerPrice = formerPrice.add(itemSku.getViewPrices()[1].multiply(new BigDecimal(item.getQuantity())));
  				}
  				BigDecimal packagePrice = null;
  				if (this.getSalePrice() != null) {
  					packagePrice = this.getSalePrice();
  				} else if (this.getDiscountPrice()!=null && this.getDiscountPrice().compareTo(this.getPrice()) != 0) {
  					packagePrice = this.getDiscountPrice();
  				} else {
  					packagePrice = this.getPrice();
  				} 
  				return new BigDecimal[]{formerPrice,packagePrice};
  				
  			default:
  				return null;
  		
  		}
  	}

	
	

	/**
	 * Default Empty Constructor for class ProductSku
	 */
	public ProductSku () {
		super();
	}
	
	/**
	 * 定义实体的业务名取值；
	 */
	public String getProductSkuName () {
		if (productSkuId == null)
	        return "";
	    else
			return this.getProduct().getProductName()+" ("+this.getProductSkuCode()+") "+this.getOrderSkuDisplayOption();
	}
	
	/**
	 * Default Key Fields Constructor for class ProductSku
     * @param in_productSkuId SKU id
	 */
	public ProductSku (Integer in_productSkuId) {
		super (in_productSkuId);
	}

	public void setProductSkuStatus(Short productSkuStatus) {
		this.status = productSkuStatus;
	}

	
	
	public BigDecimal getDiscountPrice() {
		return discountPrice;
	}

	public void setDiscountPrice(BigDecimal discountPrice) {
		this.discountPrice = discountPrice;
	}

	public BigDecimal getDiscountPriceRAM() {
		return discountPriceRAM;
	}

	public void setDiscountPriceRAM(BigDecimal discountPriceRAM) {
		this.discountPriceRAM = discountPriceRAM;
	}
	
	
	public BigDecimal getDiscountPercent() {
		return discountPercent;
	}

	public void setDiscountPercent(BigDecimal discountPercent) {
		this.discountPercent = discountPercent;
	}

	public boolean isHasDiscount() {
		return hasDiscount;
	}

	public void setHasDiscount(boolean hasDiscount) {
		this.hasDiscount = hasDiscount;
	}

	/**
	 * 构建简单的Json对象主要用于选择器
	 * @return json String
	 */
	public String getJsonObject(){
		JSONObject jsonProductSku=new JSONObject();
		jsonProductSku.put("productSkuId",this.productSkuId);
		jsonProductSku.put("productSkuCode",this.productSkuCode);
		jsonProductSku.put("price",this.price);
		jsonProductSku.put("salePrice",this.salePrice);
		jsonProductSku.put("imageUrl",this.imageUrl);
		Map<String,Object> product=new HashMap<String, Object>();
		product.put("productId",this.getProduct().getProductId());
		product.put("productName",this.getProduct().getProductName());
		product.put("productCode", this.getProduct().getProductCode());
		Map<String,Object> brand=new HashMap<String, Object>();
		brand.put("brandId",this.getProduct().getBrand()==null?"":this.getProduct().getBrand().getBrandId());
		brand.put("brandName",this.getProduct().getBrand()==null?"":this.getProduct().getBrand().getBrandName());
		product.put("brand",brand);
		jsonProductSku.put("product",product);
		return jsonProductSku.toString(); 
	}
	

	public PRule getPrule() {
		return prule;
	}

	public void setPrule(PRule prule) {
		this.prule = prule;
	}


	public String getOrderSkuDisplayOption(){
		Set<ProductSkuOptionValue> psos = this.getProductSkuOptionValues();
		String displayOptions = "";
		StringBuffer buf = new StringBuffer();
		for(ProductSkuOptionValue pso:psos){
			buf.append(pso.getSkuOptionValue().getSkuOption().getSkuOptionName()).append(":").append(pso.getSkuOptionValue().getSkuOptionValueName()).append(";");
		}
		displayOptions = buf.toString();
		if(displayOptions.length()!=0){
			displayOptions = displayOptions.substring(0,displayOptions.length()-1);
		}
		return displayOptions;
	}
	
	public String getOptionValueIds() {
		return optionValueIds;
	}

	public void setOptionValueIds(String optionValueIds) {
		this.optionValueIds = optionValueIds;
	}

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    
    public boolean equals(Object object){
		return super.equals(object);
	}
	public int hashCode() {
		return super.hashCode();
	}
	//获得skuoption相关json信息 [{skuOpion:{name},skuOptionValue:{name,type,value}}]
	public String getSkuOptionInfoJson(){
		ProdMainManager prodMainManager = (ProdMainManager)ContextUtil.getSpringBeanById("prodMainManager");
		Map<SkuOption ,SkuOptionValue> map = prodMainManager.findMapOfRelatedSkuOptionAndValue(this);
		JSONArray jsonArray=new JSONArray();
		Iterator<java.util.Map.Entry<SkuOption ,SkuOptionValue>> iterator = map.entrySet().iterator();
		while(iterator.hasNext()){
			java.util.Map.Entry<SkuOption ,SkuOptionValue> entry = iterator.next(); 
			SkuOption skuOption = entry.getKey();
			SkuOptionValue skuOptionValue = entry.getValue();
			JSONObject jsonObject=new JSONObject();
			JSONObject jsonSkuOption=new JSONObject();
			JSONObject jsonSkuOptionValue=new JSONObject();
			jsonSkuOption.put("name", skuOption.getSkuOptionName());
			jsonSkuOptionValue.put("name", skuOptionValue.getSkuOptionValueName());
			jsonSkuOptionValue.put("type", skuOptionValue.getSkuOptionValueType());
			jsonSkuOptionValue.put("value", skuOptionValue.getSkuOptionValue());
			jsonObject.put("skuOption", jsonSkuOption);
			jsonObject.put("skuOptionValue", jsonSkuOptionValue);
			jsonArray.add(jsonObject);
		}
		return jsonArray.toString();
		
	}
	
	/**
	 * 获得库存状态
	 * 缺货： 可售库存 < 最少订购数量（最少值为1）
	 * 低库存： 可售库存 <= 报警数量   或者 可售库存 <= 最少订购数量（最少值为1）
	 */
	public Short getInventoryStatus(){
		if(this.getInventory().getQuantityOnHand() != null){
			if(this.getInventory().getAvailableQuantity() < (this.getProduct().getMinOrderQuantity()!=null?this.getProduct().getMinOrderQuantity():1)){
				return Inventory.INVENTORY_LACK;
			}else if( (this.getInventory().getAvailableQuantity() <= this.getInventory().getReorderMinimnm()) || (this.getInventory().getAvailableQuantity() <= (this.getProduct().getMinOrderQuantity()!=null?this.getProduct().getMinOrderQuantity():1))){
				return Inventory.INVENTORY_LOW;
			}else{
				return Inventory.INVENTORY_AVAILABLE;
			}
		}else{
			return Inventory.INVENTORY_AVAILABLE;
		}
	}

	
	 /**
	 * 是否一个实体商品
	 * @return
	 */
	public boolean getIsPhysicalProduct(){
		return getProduct().getIsPhysicalProduct();
	}
	/**
	 * 是否一个虚拟商品
	 * @return
	 */
	public boolean getIsDigitalProduct(){
		return getProduct().getIsDigitalProduct();
	}
	
	public boolean isCatalogConditionGiftRAM() {
		return isCatalogConditionGiftRAM;
	}
	
	public void setCatalogConditionGiftRAM(boolean isCatalogConditionGiftRAM) {
		this.isCatalogConditionGiftRAM = isCatalogConditionGiftRAM;
	}
	
	public String getGiftValueIds() {
		return giftValueIds;
	}
	
	public void setGiftValueIds(String giftValueIds) {
		this.giftValueIds = giftValueIds;
	}
}
